package top.szhome.framework.starter.template.engine;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Properties;

/**
 * Velocity模板引擎
 *
 * @author 唐加利
 * @date 2023/7/14
 **/
public class VelocityEngine implements TemplateEngine {

    static {
        Properties properties = new Properties();
        properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, "");
        properties.setProperty(Velocity.ENCODING_DEFAULT, StandardCharsets.UTF_8.displayName());
        properties.setProperty(Velocity.INPUT_ENCODING, StandardCharsets.UTF_8.displayName());
        properties.setProperty("file.resource.loader.unicode", "true");
        Velocity.init();
    }

    @Override
    public String process(String name, String template, Map<String, Object> context) {
        VelocityContext c = new VelocityContext(context);
        StringWriter writer = new StringWriter();
        Velocity.evaluate(c, writer, name, template);
        return writer.toString();
    }
}
